package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Message;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service(version = "1.0.0")
public class MessageApiImpl implements MessageApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param userId
     * @param id
     * @param sd     开始时间
     * @param ed     结束时间
     * @param state  查询状态
     * @return
     */
    @Override
    public PageInfo<Message> queryMessageList(Long userId, String id, Integer pageSize, Integer page, Long sd, Long ed, String sortProp, String sortOrder, String state) {
        try {
            //分页条件 利用三元运算符判断是升序还是降序,按指定字段查询
            PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by("descending".equalsIgnoreCase(sortOrder) ? Sort.Order.desc(sortProp) : Sort.Order.asc(sortProp)));

            List<Message> messageList = null;
            Query query = null;
            //userId为空，是动态审核需要用到的
            if (userId == null) {
                if (sd != -1 && sd > 0 && ed != -1 && ed > 0) {
                    /* 需要通过时间戳查询 */
                    if (StringUtils.isEmpty(id)) {
                        //id为空,则直接查询全部,已通过,已驳回,待审核
                        List<Integer> stateId = new ArrayList<>();
                        switch (state) {
                            case "all":
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd))).with(pageRequest);
                                break;
                            case "3":
                                stateId.add(2);
                                stateId.add(5);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId)).with(pageRequest);
                                break;
                            case "4":
                                stateId.add(1);
                                stateId.add(3);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId)).with(pageRequest);
                                break;
                            case "5":
                                stateId.add(4);
                                stateId.add(6);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId)).with(pageRequest);
                                break;
                        }
                        messageList = this.mongoTemplate.find(query, Message.class);
                    } else {
                        //id不为空,则根据id查询列表,并根据state查询 全部,已通过,已驳回,待审核
                        /*查询全部,已通过,已驳回,待审核*/
                        List<Integer> stateId = new ArrayList<>();
                        switch (state) {
                            case "all":
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "3":
                                stateId.add(2);
                                stateId.add(5);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "4":
                                stateId.add(1);
                                stateId.add(3);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "5":
                                stateId.add(4);
                                stateId.add(6);
                                query = Query.query(Criteria.where("created").lt(ed).andOperator(Criteria.where("created").gt(sd)).and("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                        }
                        messageList = this.mongoTemplate.find(query, Message.class);
                    }
                } else {
                    /* 不需要通过时间戳查询*/
                    List<Integer> stateId = new ArrayList<>();
                    if (StringUtils.isEmpty(id)) {
                        //id为空,则直接查询全部,已通过,已驳回,待审核
                        switch (state) {
                            case "all":
                                query = new Query().with(pageRequest);
                                break;
                            case "3":
                                stateId.add(2);
                                stateId.add(5);
                                query = Query.query(Criteria.where("state").in(stateId)).with(pageRequest);
                                break;
                            case "4":
                                stateId.add(1);
                                stateId.add(3);
                                query = Query.query(Criteria.where("state").in(stateId)).with(pageRequest);
                                break;
                            case "5":
                                stateId.add(4);
                                stateId.add(6);
                                query = Query.query(Criteria.where("state").in(stateId)).with(pageRequest);
                                break;
                        }
                        messageList = this.mongoTemplate.find(query, Message.class);
                    } else {
                        //id不为空,则根据id查询列表,并根据state查询 全部,已通过,已驳回,待审核
                        switch (state) {
                            case "all":
                                query = Query.query(Criteria.where("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "3":
                                stateId.add(2);
                                stateId.add(5);
                                query = Query.query(Criteria.where("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "4":
                                stateId.add(1);
                                stateId.add(3);
                                query = Query.query(Criteria.where("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                            case "5":
                                stateId.add(4);
                                stateId.add(6);
                                query = Query.query(Criteria.where("state").in(stateId).and("userId").is(Integer.parseInt(id))).with(pageRequest);
                                break;
                        }
                        messageList = this.mongoTemplate.find(query, Message.class);
                    }
                }
            } else {
                /*
                    通过userId查询他参与评论,点赞,喜欢的动态,进行分页,从quanzi_comment表中查，是查询个人用到的（需要用到userId）
                    这个判断里没有用到id, 也没用到时间排序
                    直接查询跟userId相关的内容
                */
                List<Comment> commentList = this.mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Comment.class);
                if (CollectionUtils.isEmpty(commentList)) {
                    return null;
                }
                Set<ObjectId> publishIds = commentList.stream().map(Comment::getPublishId).collect(Collectors.toSet());
                query = Query.query(Criteria.where("publishId").in(publishIds));
                messageList = this.mongoTemplate.find(query, Message.class);
            }
            PageInfo<Message> pageInfo = new PageInfo<>();
            pageInfo.setPageNum(page);
            pageInfo.setPageSize(pageSize);
            pageInfo.setTotal(messageList.size());
            pageInfo.setRecords(messageList);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 置顶消息
     *
     * @param publishId
     * @return
     */
    @Override
    public Boolean topOrUnTop(String publishId, Integer topState) {
        try {
            Query query = null;
            Update update = null;
            switch (topState) {
                case 1:
                    query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
                    update = Update.update("topState", 1);
                    break;
                case 2:
                    query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
                    update = Update.update("topState", 2);
                    break;
            }
            this.mongoTemplate.updateFirst(query, update, Message.class);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Boolean passOrReject(List<String> publishIds, Integer state) {
        try {
            Query query = null;
            Update update = null;
            for (String publishId : publishIds) {
                switch (state) {
                    case 5://人工审核通过
                        query = Query.query(Criteria.where("publishId").in(new ObjectId(publishId)));
                        update = Update.update("state", 5);
                        break;
                    case 4://人工审核拒绝
                        query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)));
                        update = Update.update("state", 4);
                        break;
                }
                this.mongoTemplate.updateFirst(query, update, Message.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 消息撤销
     *
     * @param publishIds
     * @return
     */
    @Override
    public Boolean revocationMsg(List<String> publishIds) {
        try {
            for (String publishId : publishIds) {
                Query query = Query.query(Criteria.where("publishId").in(new ObjectId(publishId)));
                this.mongoTemplate.remove(query, Message.class);
            }
            return true;
        } catch (
                Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 消息详情
     *
     * @param publishId
     * @return
     */
    @Override
    public Message queryById(String publishId) {
        return this.mongoTemplate.findOne(Query.query(Criteria.where("publishId").is(new ObjectId(publishId))), Message.class);
    }
}
